package com.ruoyi.system.service.impl;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.domain.IaeVoucher;
import com.ruoyi.system.mapper.IaeVoucherMapper;
import com.ruoyi.common.core.web.domain.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.IaeInternalTransferMapper;
import com.ruoyi.system.domain.IaeInternalTransfer;
import com.ruoyi.system.service.IIaeInternalTransferService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 内部转账记录Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-02-27
 */
@Service
@Transactional
public class IaeInternalTransferServiceImpl implements IIaeInternalTransferService
{
    @Autowired
    private IaeInternalTransferMapper iaeInternalTransferMapper;

    @Autowired
    private IaeVoucherMapper voucherMapper;

    /**
     * 查询内部转账记录
     * 
     * @param id 内部转账记录主键
     * @return 内部转账记录
     */
    @Override
    public IaeInternalTransfer selectIaeInternalTransferById(Long id)
    {
        return iaeInternalTransferMapper.selectIaeInternalTransferById(id);
    }

    /**
     * 查询内部转账记录列表
     * 
     * @param iaeInternalTransfer 内部转账记录
     * @return 内部转账记录
     */
    @Override
    public List<IaeInternalTransfer> selectIaeInternalTransferList(IaeInternalTransfer iaeInternalTransfer)
    {
        return iaeInternalTransferMapper.selectIaeInternalTransferList(iaeInternalTransfer);
    }

    /**
     * 新增内部转账记录
     * 
     * @param iaeInternalTransfer 内部转账记录
     * @return 结果
     */
    @Override
    public int insertIaeInternalTransfer(IaeInternalTransfer iaeInternalTransfer)
    {

        //转入转出账户不能一致
        if (iaeInternalTransfer.getAccountJoin().equals(iaeInternalTransfer.getAccountOut()) ){
            AjaxResult.error("转入转出账户不能一致");
        }

        iaeInternalTransfer.setCreateTime(DateUtils.getNowDate());
        return iaeInternalTransferMapper.insertIaeInternalTransfer(iaeInternalTransfer);
    }

    /**
     * 修改内部转账记录
     * 
     * @param iaeInternalTransfer 内部转账记录
     * @return 结果
     */
    @Override
    public int updateIaeInternalTransfer(IaeInternalTransfer iaeInternalTransfer)
    {
        return iaeInternalTransferMapper.updateIaeInternalTransfer(iaeInternalTransfer);
    }

    /**
     * 批量删除内部转账记录
     * 
     * @param ids 需要删除的内部转账记录主键
     * @return 结果
     */
    @Override
    public int deleteIaeInternalTransferByIds(Long[] ids)
    {
        return iaeInternalTransferMapper.deleteIaeInternalTransferByIds(ids);
    }

    /**
     * 删除内部转账记录信息
     * 
     * @param id 内部转账记录主键
     * @return 结果
     */
    @Override
    public int deleteIaeInternalTransferById(Long id)
    {
        return iaeInternalTransferMapper.deleteIaeInternalTransferById(id);
    }

    @Override
    public String importTransfer(List<IaeInternalTransfer> transferList, boolean updateSupport, String operName) {
        if (StringUtils.isNull(transferList) || transferList.size() == 0) {
            return "导入数据不能为空！";
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (IaeInternalTransfer transfer : transferList) {
            try {
                // 验证是否存在这个用户
                IaeInternalTransfer t = iaeInternalTransferMapper.selectTransferById(Math.toIntExact(transfer.getId()));
                if (StringUtils.isNull(t)) {
                    transfer.setCreateBy(operName);
                    this.insertTransfer(transfer);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + transfer.getId() + " 导入成功");
                } else if (updateSupport) {
                    transfer.setUpdateBy(operName);
                    this.updateTransfer(transfer);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + transfer.getId() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + transfer.getId() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + transfer.getId() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }

        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            return failureMsg.toString();
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public void insertTransfer(IaeInternalTransfer transfer) {
        iaeInternalTransferMapper.insertIaeInternalTransfer(transfer);
    }

    @Override
    public void updateTransfer(IaeInternalTransfer transfer) {
        iaeInternalTransferMapper.updateIaeInternalTransfer(transfer);
    }

    @Override
    public IaeVoucher generateVoucher(IaeInternalTransfer iaeInternalTransfer) {
        // 1. 检查凭证字号是否已存在
        String voucherNumber = iaeInternalTransfer.getVoucherDetailsId() + "-" + iaeInternalTransfer.getVoucherDetailsId();
        IaeVoucher existVoucher = voucherMapper.checkVoucherExists(iaeInternalTransfer.getVoucherDetailsId());
        if (existVoucher != null) {
            throw new ServiceException("凭证字号 " + voucherNumber + " 已存在！");
        }

        // 2. 获取内部转账记录
        IaeInternalTransfer transfer = iaeInternalTransferMapper.selectTransferById(Math.toIntExact(iaeInternalTransfer.getId()));
        if (transfer == null) {
            throw new ServiceException("找不到对应的内部转账记录");
        }

        // 3. 创建凭证记录
        IaeVoucher voucher = new IaeVoucher();
        voucher.setVoucherDate(iaeInternalTransfer.getCreateTime());
        voucher.setVoucherWordId(iaeInternalTransfer.getVoucherDetailsId());
        // 设置凭证摘要
        voucher.setVoucherAbstract(StringUtils.isNotEmpty(iaeInternalTransfer.getInsideAbstract()) ?
                iaeInternalTransfer.getInsideAbstract() : transfer.getInsideAbstract());

        // 设置科目ID - 从accountCode转换或使用默认值
        Long accountId = null;
        try {
            accountId = Long.parseLong(String.valueOf(iaeInternalTransfer.getAccountJoin()));
        } catch (NumberFormatException e) {
            // 使用默认科目ID，可以根据业务需求调整
            accountId = 1001L; // 默认科目ID
        }
        voucher.setAccountId(accountId);

        // 设置借贷金额
        BigDecimal amount = transfer.getAccountLimit();
        voucher.setDebitAmount(String.valueOf(amount));
        voucher.setCreditAmount(String.valueOf(amount));

        // 设置凭证字ID - 根据凭证字转换
        Long voucherWordId = null;
        if ("J".equals(iaeInternalTransfer.getVoucherDetailsId())) {
            voucherWordId = 1L; // 记账凭证
        } else if ("S".equals(iaeInternalTransfer.getVoucherDetailsId())) {
            voucherWordId = 2L; // 收款凭证
        } else if ("F".equals(iaeInternalTransfer.getVoucherDetailsId())) {
            voucherWordId = 3L; // 付款凭证
        } else {
            voucherWordId = 1L; // 默认记账凭证
        }
        voucher.setVoucherWordId(voucherWordId);

        // 设置其他字段
        voucher.setRemark(iaeInternalTransfer.getRemark());
        voucher.setCreateBy(SecurityUtils.getUsername());
        voucher.setCreateTime(DateUtils.getNowDate());

        // 4. 保存凭证
        voucherMapper.insertVoucher(voucher);

        // 5. 插入内部转账记录关联
        //saveTransferVoucherRelation(voucher.getId(), transfer);

        return voucher;
    }


}
